<template>
  <div class="login-container">
    <div class="login-box">
      <h2>{{ isLogin ? '登录' : '注册' }}</h2>
      
      <div class="input-group">
        <input 
          type="text" 
          v-model="username" 
          placeholder="用户名"
          @keyup.enter="handleSubmit"
        >
        <input 
          type="password" 
          v-model="password" 
          placeholder="密码"
          @keyup.enter="handleSubmit"
        >
        <input 
          v-if="!isLogin" 
          type="password" 
          v-model="confirmPassword" 
          placeholder="确认密码"
          @keyup.enter="handleSubmit"
        >
      </div>

      <div class="btn-group">
        <button @click="handleSubmit">
          {{ isLogin ? '登录' : '注册' }}
        </button>
        <p>
          <span @click="isLogin = !isLogin">
            {{ isLogin ? '没有账号？去注册' : '已有账号？去登录' }}
          </span>
          <router-link v-if="isLogin" to="/reset-password">
            忘记密码？
          </router-link>
        </p>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'LoginComponent',
  data() {
    return {
      isLogin: true,
      username: '',
      password: '',
      confirmPassword: ''
    }
  },
  created() {
    // 检查并清理重复的管理员账号
    const users = JSON.parse(localStorage.getItem('users') || '[]');
    
    // 如果有多个admin用户，只保留最新的一个
    const adminUsers = users.filter(user => user.username === 'admin');
    if (adminUsers.length > 1) {
        // 按注册时间排序，保留最新的
        const latestAdmin = adminUsers.sort((a, b) => 
            new Date(b.registerTime) - new Date(a.registerTime)
        )[0];
        
        // 清除其他admin账号
        const cleanedUsers = users.filter(user => 
            user.username !== 'admin' || user === latestAdmin
        );
        
        localStorage.setItem('users', JSON.stringify(cleanedUsers));
    }
    
    // 如果没有任何用户，创建默认管理员账号
    if (users.length === 0) {
        const adminUser = {
            username: 'admin',
            password: 'admin123',
            isAdmin: true,
            registerTime: new Date().format('yyyy/MM/dd HH:mm:ss'),
            avatarUrl: ''
        };
        localStorage.setItem('users', JSON.stringify([adminUser]));
    }
  },
  methods: {
    handleSubmit() {
      if(!this.username || !this.password) {
        alert('请填写完整信息');
        return;
      }

      if(!this.isLogin && this.password !== this.confirmPassword) {
        alert('两次密码不一致');
        return;
      }

      const users = JSON.parse(localStorage.getItem('users') || '[]');

      if(this.isLogin) {
        // 登录逻辑
        const user = users.find(u => u.username === this.username && u.password === this.password);
        if(user) {
          // 先更新 localStorage
          localStorage.setItem('currentUser', JSON.stringify(user))
          
          // 如果 store 可用，也更新 store
          if (this.$store?.commit) {
            this.$store.commit('updateUser', user)
          }
          
          // 更新最后登录时间
          user.lastLoginTime = new Date().toISOString()
          localStorage.setItem('users', JSON.stringify(users))
          
          // 获取重定向地址
          const redirect = this.$route.query.redirect || '/'
          window.location.href = redirect
        } else {
          alert('用户名或密码错误');
        }
      } else {
        // 注册逻辑
        if(users.some(u => u.username === this.username)) {
          alert('用户名已存在');
          return;
        }
        const newUser = {
          username: this.username,
          password: this.password,
          isAdmin: false,
          registerTime: new Date().format('yyyy/MM/dd HH:mm:ss'),
          avatarUrl: ''
        }
        users.push(newUser)
        localStorage.setItem('users', JSON.stringify(users))
        this.isLogin = true;
        alert('注册成功，请登录');
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.login-container {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f5f5;

  .login-box {
    width: 360px;
    padding: 30px;
    background: white;
    border-radius: 4px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);

    h2 {
      text-align: center;
      margin-bottom: 25px;
      color: #333;
      font-size: 20px;
    }

    .input-group {
      display: flex;
      flex-direction: column;
      gap: 15px;
      margin-bottom: 20px;

      input {
        padding: 12px;
        border: 1px solid #ddd;
        border-radius: 4px;
        font-size: 14px;
        
        &:focus {
          outline: none;
          border-color: #ee7419;
        }
      }
    }

    .btn-group {
      button {
        width: 100%;
        padding: 12px;
        background: #ee7419;
        color: white;
        border: none;
        border-radius: 4px;
        cursor: pointer;
        font-size: 14px;
      }

      p {
        margin-top: 15px;
        text-align: center;
        font-size: 14px;
        
        span, a {
          color: #ee7419;
          cursor: pointer;
          margin: 0 5px;
        }
      }
    }
  }
}
</style> 